package com.momo.service.sysSetting;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.momo.common.common.JSONResult;
import com.momo.common.req.sysSetting.user.SysUserReq;
import com.momo.common.req.sysmain.RedisUser;
import com.momo.common.util.DateUtil;
import com.momo.common.util.Encrypt;
import com.momo.common.util.JwtTokenUtil;
import com.momo.common.util.StrUtil;
import com.momo.mapper.dataobject.RoleDO;
import com.momo.mapper.dataobject.UserDO;
import com.momo.mapper.mapper.sysSetting.UserMapper;
import com.momo.mapper.mapper.sysmain.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Kagome on 2019/4/20.
 */
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public JSONResult userPage(SysUserReq sysUserReq, RedisUser redisUser) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(sysUserReq, userDO);

        userDO.setGroupId(redisUser.getGroupId());
        PageHelper.startPage(sysUserReq.getPageNum(), sysUserReq.getPageSize(), "id desc");
        List<UserDO> list = userMapper.userPage(userDO);
        PageInfo<UserDO> pageInfo = new PageInfo<>(list);
        //以下采用硬编码方式
        if (redisUser.getGroupId().equals(1L)) {//总部登录
            //超级管理员登录
            if (redisUser.getId().equals(1L)) {
                return JSONResult.ok(pageInfo);
            } else {
                //非超级管理员登录，剔除掉超级管理员信息
                List<UserDO> userDOList = pageInfo.getList();
                PageInfo<UserDO> finalPageInfo = pageInfo(userDOList, pageInfo, 1L);
                return JSONResult.ok(finalPageInfo);
            }
        } else {//企业登录/第三方登录
//            if (redisUser.isAdminRole()) {//如果是管理员
//                return JSONResult.ok(pageInfo);
//            } else {
                //非管理员登录，剔除掉管理员信息
                List<UserDO> userDOList = pageInfo.getList();
                PageInfo<UserDO> finalPageInfo = pageInfo(userDOList, pageInfo, redisUser.getId());
                return JSONResult.ok(finalPageInfo);
//            }
        }
    }

    private PageInfo<UserDO> pageInfo(List<UserDO> userDOList, PageInfo<UserDO> pageInfo, Long userId) {
        List<UserDO> finalUserList = Lists.newArrayList();
        //此处采用硬编码方式，非超级管理员登录，剔除掉超级管理员信息
        userDOList.forEach(userDO1 -> {
            if (!userDO1.getId().equals(userId)) {
                finalUserList.add(userDO1);
            }
        });
        PageInfo<UserDO> finalPageInfo = new PageInfo<>(finalUserList);
        finalPageInfo.setTotal(pageInfo.getTotal());
        finalPageInfo.setPageNum(pageInfo.getPageNum());
        finalPageInfo.setPageSize(pageInfo.getPageSize());
        return finalPageInfo;
    }

    @Override
    public JSONResult userStatus(SysUserReq sysUserReq, RedisUser redisUser) {
        UserDO userDO = sysUserMapper.uuid(sysUserReq.getSysUserUuid());
        if (null == userDO) {
            return JSONResult.errorMap("待编辑的用户不存在");
        }
        String statusMsg = "";
        //状态 0启用  1禁用
        if ("0".equals(sysUserReq.getIsForbidden())) {
            userDO.setIsForbidden("1");
            statusMsg = "用户:" + sysUserReq.getSysUserName() + " 禁用 成功";
        } else if ("1".equals(sysUserReq.getIsForbidden())) {
            userDO.setIsForbidden("0");
            statusMsg = "用户: " + sysUserReq.getSysUserName() + " 启用 成功";
        }
        userDO.setUpdateBy(redisUser.getSysUserName());
        userDO.setUpdateTime(DateUtil.getDateTime());
        userMapper.updateByPrimaryKeySelective(userDO);
        return JSONResult.ok(statusMsg);
    }

    @Override
    public JSONResult detail(SysUserReq sysUserReq, RedisUser redisUser) {
        UserDO userDO = sysUserMapper.uuid(sysUserReq.getSysUserUuid());
        if (null == userDO) {
            return JSONResult.errorMap("待查询的用户不存在");
        }
        userDO.setSysUserPwd(null);
        userDO.setSysUserAuthSalt(null);
        return JSONResult.ok(userDO);
    }

    @Override
    public JSONResult userAdd(SysUserReq sysUserReq, RedisUser redisUser) {
        if (checkInfo(sysUserReq.getSysUserEmail(), null, null, null)) {
            return JSONResult.errorMap("邮箱已被使用");
        }
        if (checkInfo(null, sysUserReq.getSysUserPhone(), null, null)) {
            return JSONResult.errorMap("手机号已被使用");
        }
        if (checkInfo(null, null, sysUserReq.getSysUserLoginName(), null)) {
            return JSONResult.errorMap("登录账号已被使用");
        }
        final String randomKey = jwtTokenUtil.getRandomKey();
        String pwd = Encrypt.getShiroPassword(sysUserReq.getSysUserPwd(), randomKey, 2);
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(sysUserReq, userDO);
        userDO.setSysUserPwd(pwd);
        userDO.setSysUserAuthSalt(randomKey);
        userDO.setGroupId(redisUser.getGroupId());
        userDO.setCreateBy(redisUser.getSysUserName());
        userDO.setUpdateBy(redisUser.getSysUserName());
        userDO.setCreateTime(DateUtil.getDateTime());
        userDO.setUpdateTime(DateUtil.getDateTime());
        userDO.setSysUserUuid(StrUtil.genUUID());
        userMapper.insertSelective(userDO);
        return JSONResult.ok("新增用户成功");
    }

    @Override
    public JSONResult modify(SysUserReq sysUserReq, RedisUser redisUser) {
        UserDO userDO = sysUserMapper.uuid(sysUserReq.getSysUserUuid());
        if (null == userDO) {
            return JSONResult.errorMap("待编辑的用户不存在");
        }
        if (checkInfo(sysUserReq.getSysUserEmail(), null, null, userDO.getId())) {
            return JSONResult.errorMap("邮箱已被使用");
        }
        if (checkInfo(null, sysUserReq.getSysUserPhone(), null, userDO.getId())) {
            return JSONResult.errorMap("手机号已被使用");
        }
        if (checkInfo(null, null, sysUserReq.getSysUserLoginName(), userDO.getId())) {
            return JSONResult.errorMap("登录账号已被使用");
        }
        BeanUtils.copyProperties(sysUserReq, userDO);
        userDO.setSysUserPwd(null);
        userDO.setUpdateBy(redisUser.getSysUserName());
        userDO.setUpdateTime(DateUtil.getDateTime());
        userMapper.updateByPrimaryKeySelective(userDO);
        return JSONResult.ok("编辑用户成功");
    }

    @Override
    public JSONResult changePwd(SysUserReq sysUserReq, RedisUser redisUser) {
        //todo 骚操作 ，可以加入短信或者邮箱验证
        UserDO userDO = sysUserMapper.uuid(sysUserReq.getSysUserUuid());
        if (null == userDO) {
            return JSONResult.errorMap("待查询的用户不存在");
        }
        if (!sysUserReq.getSysUserPwd().equals(sysUserReq.getCheckPass())) {
            return JSONResult.errorMap("两次密码不一致");
        }
        final String randomKey = jwtTokenUtil.getRandomKey();
        String pwd = Encrypt.getShiroPassword(sysUserReq.getSysUserPwd(), randomKey, 2);
        userDO.setSysUserPwd(pwd);
        userDO.setSysUserAuthSalt(randomKey);
        userMapper.updateByPrimaryKeySelective(userDO);

        return JSONResult.ok("修改密码成功");
    }

    private boolean checkInfo(String sysUserEmail, String sysUserPhone, String sysUserLoginName, Long id) {
        return userMapper.checkInfo(sysUserEmail, sysUserPhone, sysUserLoginName, id) > 0 ? true : false;
    }
}
